import { NextRequest, NextResponse } from 'next/server';
import OpenAI from 'openai';
import prisma from '@/lib/prisma';
import { getUser } from '@/lib/authUtils';

const openai = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: process.env.OPENAI_API_KEY,
});

export async function GET(
  request: NextRequest,
  { params }: { params: { copy_id: string } }
): Promise<Response> {
  try {
    const userid = await getUser(request);
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      );
    }
    if (userid instanceof NextResponse) {
      return userid;
    }

    const { copy_id } = params;
    if (!copy_id) {
      return NextResponse.json(
        { error: '文案ID不能为空' }, 
        { status: 400 }
      );
    }

    const copy = await prisma.vms_copy.findUnique({
      where: { id: copy_id }
    });

    if (!copy) {
      return NextResponse.json({ error: 'Copy not found' }, { status: 404 });
    }

    if (!copy.rich_content) {
      return NextResponse.json({ error: 'No rich content found' }, { status: 400 });
    }

   
    const prompt = 
    `请根据以下文案内容创建PPT演示文稿：
    1. 第一页为标题页，使用文案标题
    2. 将内容分解为逻辑清晰的部分，每一页聚焦一个核心观点
    3. 提炼关键信息、数据点和结论
    4. 每个幻灯片包含：
       - 一个明确的主题标题
       - 3-5个简洁的关键点
       - 必要时使用项目符号
       - 使用Markdown格式
    5. 保持内容简洁，避免口语化表达长篇大论
    6. 幻灯片之间用---分隔
    7. 确保内容连贯，符合商业演示标准
    8. 只返回ppt内容

    文案内容：
    ${copy.rich_content}`;

    const completion = await openai.chat.completions.create({
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: prompt }
      ],
      model: "deepseek-reasoner",
    });

    const pptContent = completion.choices[0].message.content || '';

    const cleanedPptContent = pptContent
      .replace(/```markdown/g, '')
      .replace(/```/g, '')
      .trim();

    if (!cleanedPptContent) {
      return NextResponse.json({ error: 'Failed to generate PPT content' }, { status: 500 });
    }

    const updatedCopy = await prisma.vms_copy.update({
      where: { id: copy_id },
      data: { ppt_content: cleanedPptContent },
    });

    return NextResponse.json(updatedCopy);

  } catch (error) {
    console.error('Error generating PPT:', error);
    return NextResponse.json(
      { error: 'Internal Server Error' },
      { status: 500 }
    );
  }
}
